package com.fg.core;

import cn.hutool.core.io.file.FileWriter;
import com.fg.utils.CurrentJarDirectoryUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 王富贵
 * @description: 文件输出工具
 * @createTime: 2024年04月21日 19:43:54
 */
@Slf4j
public class FileWrite {

    private static final AtomicInteger fileNumber = new AtomicInteger(0);
    private static FileWriter fileWriter = null;

    public FileWrite() {
        createFile(null, null);
    }
    public FileWrite(String fileName) {
        createFile(fileName);
    }
    public FileWrite(String filePath, String fileName) {
        createFile(filePath, fileName);
    }

    public void createFile() {
        createFile(null, null);
    }


    public void createFile(String fileName) {
        createFile(null, fileName);
    }


    public void createFile(String filePath, String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            fileName = String.valueOf(fileNumber.incrementAndGet());
        }
        if (StringUtils.isEmpty(filePath)) {
            fileWriter = new FileWriter(CurrentJarDirectoryUtil.getFileNameBySuffixSQL(fileName));
        } else {
            fileWriter = new FileWriter(filePath + File.separator + fileName);
        }
    }

    public void write(String sql) {
        if (StringUtils.isEmpty(sql)) {
            return;
        }
        if (Objects.isNull(fileWriter)) {
            createFile();
        }
        fileWriter.append(sql + CurrentJarDirectoryUtil.lineSeparator);
    }

    public void write(Collection sqlList){
        if (Objects.isNull(sqlList) || sqlList.isEmpty()) {
            return;
        }
        if (Objects.isNull(fileWriter)) {
            createFile();
        }
        fileWriter.appendLines(sqlList);
    }
}
